package com.ankur.calllogger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ankur.calllogger.dao.Account;
import com.ankur.calllogger.dao.CallDetail;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.NotFoundException;

@SuppressWarnings("serial")
public class MainServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(MainServlet.class
			.getName());

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		Account account = null;
		if (user != null) {
			account = Account.findByEmail(user.getEmail());
			List<CallDetail> callDetailsList = account
					.listAllCallDetailByDate();
			JSONArray jsonArray = new JSONArray();
			for (CallDetail callDetail : callDetailsList) {
				jsonArray.put(callDetail.toJSON());
			}
			resp.setContentType("text/plain");
			resp.getWriter().println(jsonArray.toString());
		} else {
			log.warning("Not logged In.");
			resp.setContentType("text/html");
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String callRecords = req.getParameter("callrecords");

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		Account account = null;
		try {
			account = Account.findByEmail(user.getEmail());
		} catch (NotFoundException nfe) {
			(new Account(user.getEmail(), user.getUserId(), user.getNickname()))
					.save();
			account = Account.findByEmail(user.getEmail());
		}

		long firstDate = -1;
		if (user != null) {
			try {
				JSONArray records = new JSONArray(callRecords);
				List<CallDetail> callDetailList = new ArrayList<CallDetail>();
				for (int i = 0; i < records.length(); i++) {
					JSONObject record = records.getJSONObject(i);
					CallDetail callDetail = new CallDetail(record
							.getString("deviceid"), user.getEmail(), record
							.getLong("_id"), record.getString("number"), record
							.getLong("duration"), new Date(record
							.getLong("date")), record.optString("name",
							"New Number"), record.getInt("type"));
					callDetailList.add(callDetail);
					if (i == 0) {
						firstDate = record.getLong("date");
					}
				}
				account.addCallDetails(callDetailList);
			} catch (JSONException e) {
				log.severe("Error while parsing : " + e.getMessage());
			}
			resp.setContentType("text/plain");
			resp.getWriter().println(firstDate);
		} else {
			log.warning("Not logged In.");
			resp.setContentType("text/html");
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
	}
}